﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ConsumerClient.ServiceReference1;
using System.Security.Cryptography;
using System.ServiceModel;

namespace ConsumerClient
{
    /// <summary>
    /// Interaction logic for Login.xaml
    /// </summary>
    public partial class Login : Window
    {
        public WCFUser LoginUser { get; set; }
        private PlanRouteServiceClient client;

        public Login()
        {
            InitializeComponent();
        }

        public Login(PlanRouteServiceClient client)
        {
            this.client = client;
            InitializeComponent();
        }

        private async void btn_Login_Click(object sender, RoutedEventArgs e)
        {
            btn_Login.IsEnabled = false;
            string passwordToken = HashPassword(pwb_password.Password);
            //PlanRouteServiceClient client = new PlanRouteServiceClient();
            //WCFUser user = null;
            Task<WCFUser> getUser = client.LoginAsync(txt_User.Text, passwordToken);
            WCFUser user = null;
            try
            {
                user = await getUser;
            }
            catch (FaultException fe)
            {
                MessageBox.Show(fe.Message);
            }
            finally
            {
                if (client.InnerChannel.State == CommunicationState.Faulted) {
                    client.Abort();
                    //((IDisposable)client).Dispose();
                    client = new PlanRouteServiceClient();
                }
            }
            if (user == null)
            {
                pwb_password.Password = string.Empty;
                txt_User.Text = string.Empty;
                btn_Login.IsEnabled = true;
            }
            else
            {
                this.LoginUser = user;
                this.DialogResult = true;
                this.Close();
            }
        }

        private string HashPassword(string input)
        {
            // password hashing happends here
            byte[] passwordByte = System.Text.Encoding.UTF8.GetBytes(input);
            SHA512 sMa = new SHA512Managed();
            byte[] hashResult = sMa.ComputeHash(passwordByte);
            return HashToString(hashResult);
        }

        private string HashToString(byte[] input)
        {
            string output = BitConverter.ToString(input);
            return output.Replace("-", "").ToLower();
        }
    }
}
